// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

// ============================== 导出工具 ============================== //

export default {
  /**
   * 获取聚合列表
   */
  getGatherList(pointList, gapWP, gapHP, showAll) {
    const tranOnline = (obj) => obj.objectRunStatus === '1'
    const list = pointList.filter((item) => item.left !== null && item.top !== null)
      .map((item) => ({
        id: `gather-${item.id}`,
        left: item.left,
        top: item.top,
        online: tranOnline(item),
        points: [{ ...item, online: tranOnline(item) }],
      }))

    // 原图时，显示全部点位
    if (showAll) return list

    // 查询满足合并的两项
    const getMinIJ = () => {
      let [miniWP, miniHP] = [100, 100]
      let minI, minJ
      for (let i = 0; i < list.length - 1; i++) {
        for (let j = i + 1; j < list.length; j++) {
          const myWP = Math.abs(list[j].left - list[i].left) // 横向差
          const myHP = Math.abs(list[j].top - list[i].top) // 纵向差
          if (myWP < gapWP && myHP < gapHP) {
            const isLess = myWP + myHP < miniWP + miniHP
            if (isLess) [miniWP, miniHP, minI, minJ] = [myWP, myHP, i, j]
          }
        }
      }
      return miniWP < gapWP && miniHP < gapHP ? [minI, minJ] : null
    }

    // 首轮查找
    let ij = getMinIJ()

    // 循环判断
    while (ij) {
      const [i, j] = ij

      // 合并后重新计算
      list[i].points.push(...list[j].points)
      list[i].left = CORE.div(list[i].points.reduce((total, item) => total + item.left, 0), list[i].points.length)
      list[i].top = CORE.div(list[i].points.reduce((total, item) => total + item.top, 0), list[i].points.length)
      list[i].online = list[i].points.reduce((bool, item) => bool || item.online, false)

      // 删除被合并项
      list.splice(j, 1)

      // 下一轮查找
      ij = getMinIJ()
    }

    // 按聚合数排序，聚合的越多，越不会被遮挡
    list.sort((a, b) => a.points.length - b.points.length)

    return list
  },
}
